package com.moonbird.springboot.controller;

import com.moonbird.springboot.DTO.Result;
import com.moonbird.springboot.Utils.JwtUtils;
import com.moonbird.springboot.pojo.User;
import com.moonbird.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录和注册界面的管理器
 * @author hpl
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户登录
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        Result<String> result = userService.login(user);
        if (result.getCode() == 0){
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",user.getUsername());
            claims.put("password",user.getPassword());
            String jwt = JwtUtils.generateJwt(claims);
            result.setData(jwt);
            result.setMessage("登录成功!");
        }
        return result;
    }

    // 用户注册
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        return userService.register(user);
    }

    //用户修改密码
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody User user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        return userService.updatePassword(user);
    }
}
